package cn.xfdzx.android.apps.shop.base;


import android.content.Context;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;

import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import cn.xfdzx.android.apps.shop.util.ProgressDialog;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;

/**
 * @author lfh
 * 加入绑定生命周期，防止MVP泄露
 * @data 2020/03/25
 */
public abstract class MvpBaseFragment<T extends BasePresenterImp> extends BaseFragment implements BaseView {

    protected T mPresenter;

    public abstract T createPresenter();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = createPresenter();
        mPresenter.attachView(this);
    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroy();
    }

    /**
     * 绑定生命周期 防止MVP内存泄漏
     *
     * @param <T>
     * @return
     */
    @Override
    public <T> AutoDisposeConverter<T> bindAutoDispose() {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(getActivity(), Lifecycle.Event.ON_DESTROY));
    }

    public Context getMContext() {
        return mContext;
    }

    @Override
    public void showLoading() {
        if (TYPE_IS_RETAIL == 1) {
            if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
                ProgressDialog.getInstance().show(getActivity());
            }
        }
    }

    @Override
    public void hideLoading() {
        if (TYPE_IS_RETAIL == 1) {
            ProgressDialog.getInstance().dismiss();
        }
    }

}
